import React, { useRef, useState, useEffect } from "react";
import { Card, message, Button, Upload, Form, Image, Modal, Input } from "antd";
import type { ActionType, ProColumns } from "@ant-design/pro-components";
import { EditableProTable, BetaSchemaForm } from "@ant-design/pro-components";
import request, { handleRes } from "@/utils/request";
import { PlusOutlined } from "@ant-design/icons";
import type { UploadFile } from "antd/es/upload/interface";
import ProductForm from "./components/ProductForm";
import { api } from "@/utils/env";
import { productApi } from "./api";
import DeleteConfirm from "@/components/DeleteConfirm";
import useDeleteConfirm from "@/components/DeleteConfirm/useDeleteConfirm";
import useToolBar from "@/components/PcTable/hooks/useToolBar";
import useColumnOptions from "@/components/PcTable/hooks/useColumnOptions";
import useColumns from "@/components/PcTable/hooks/useColumns";
import usePcPage from "@/components/PcPage/hooks/usePcPage";
import PcPage from "@/components/PcPage";

interface ProductItem {
  id: string;
  name: string;
  purchasePrice: number;
  marketPrice: number;
  batchNo: string;
  notice?: string;
  categoryId: string;
  brandId: string;
  sort: number;
  status: boolean;
  mainImage: string;
  categoryName: string;
  brandName: string;
  images: string[];
  priceHistory?: {
    date: string;
    marketPrice: number;
    purchasePrice: number;
  }[];
}

export interface PageType {
  id: string;
  name: string;
  sort: number;
  status: boolean;
  remark?: string;
}

export interface PageParams {
  name?: string;
  status?: boolean;
  page?: number;
  pageSize?: number;
}

const ProductList: React.FC = () => {
  const [editableKeys, setEditableKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();
  const [dataSource, setDataSource] = useState<ProductItem[]>([]);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<ProductItem>();
  const [selectedCategory, setSelectedCategory] = useState<string>();
  const [selectedBrand, setSelectedBrand] = useState<string>();
  const [brandOptions, setBrandOptions] = useState<
    { label: string; value: string }[]
  >([]);
  const [queryParams, setQueryParams] = useState({
    categoryId: undefined,
    brandId: undefined,
    current: 1,
  });
  const [verificationModalVisible, setVerificationModalVisible] =
    useState(false);
  const [verificationRecord, setVerificationRecord] =
    useState<ProductItem | null>(null);
  const [verificationAnswer, setVerificationAnswer] = useState<string>("");
  const [verificationQuestion, setVerificationQuestion] = useState<{
    num1: number;
    num2: number;
  }>({ num1: 0, num2: 0 });

  // 2. 抽离 handleSearch 函数
  const handleSearch = async (data: PageParams, pageConfig: any) => {
    pageConfig.setTableLoading(true);
    try {
      const res = await handleRes({
        api: productApi.getList,
        data,
        returnKey: false,
      });

      pageConfig.updateDataSource(res.data.list, res.data.total);
    } finally {
      pageConfig.setTableLoading(false);
    }
  };

  // 3. 抽离 handleReset 函数
  const handleReset = (pageRef: any, pageConfig: any) => {
    pageRef.current.onSearch({
      current: pageConfig.pagination.current,
      pageSize: pageConfig.pagination.pageSize,
    });
  };

  // 使用 PcPage hook，使用抽离的函数
  const { pageRef, pageConfig } = usePcPage<PageType, PageParams>({
    defaultPageSize: 10,

    onSearch: (values) => handleSearch(values, pageConfig),
    onReset: () => handleReset(pageRef, pageConfig),
  });

  const baseColumns: ProColumns<ProductItem>[] = [
    {
      title: "商品名称",
      dataIndex: "name",
      width: 200,

      search: {
        transform: (value) => ({ name: value }),
      },
    },
    {
      title: "商品主图",
      dataIndex: "mainImage",
      width: 100,
      valueType: "image",
      render: (dom, entity, index, action, schema) => (
        <Image width={30} src={`${api}${entity.mainImage}`} />
      ),
      search: false,
    },
    {
      title: "商品图片列表",
      dataIndex: "images",
      width: 200,
      render: (dom, entity, index, action, schema) => (
        <Image.PreviewGroup>
          {entity.images.map((item, index) => (
            <Image key={index} width={30} src={`${api}${item}`} />
          ))}
        </Image.PreviewGroup>
      ),
      search: false,
    },
    {
      title: "采购价格",
      dataIndex: "purchasePrice",
      width: 120,
      valueType: "money",

      search: {
        transform: (value) => ({ purchasePrice: value }),
      },
    },
    {
      title: "市场价格",
      dataIndex: "marketPrice",
      width: 120,
      valueType: "money",

      search: {
        transform: (value) => ({ marketPrice: value }),
      },
    },
    {
      title: "批次号",
      dataIndex: "batchNo",
      width: 120,

      search: {
        transform: (value) => ({ batchNo: value }),
      },
    },
    {
      title: "商品分类",
      dataIndex: "categoryId",
      width: 120,
      valueType: "select",
      render: (_, record) => record.categoryName,
      request: async () => {
        const res = await request.get("/categories/list");

        return res?.data?.list.map((item: any) => ({
          label: item.name,
          value: item.id,
        }));
      },
      search: {
        transform: (value) => ({ categoryId: value }),
      },
    },
    {
      title: "商品品牌",
      dataIndex: "brandId",
      width: 120,
      valueType: "select",
      render: (_, record) => record.brandName,
      dependencies: ["categoryId"],
      request: async (params) => {
        const categoryId = form.getFieldValue("categoryId");
        if (!categoryId) return [];
        const res = await request.get("/brands/list", {
          params: { categoryId },
        });
        return res.data?.list?.map((item: any) => ({
          label: item.name,
          value: item.id,
        }));
      },
      search: {
        transform: (value) => ({ brandId: value }),
      },
    },
    {
      title: "排序",
      dataIndex: "sort",
      width: 80,
      valueType: "digit",
      search: false,
    },
    {
      title: "状态",
      dataIndex: "status",
      width: 80,
      valueType: "switch",
      search: {
        transform: (value) => ({ status: value }),
      },
    },
  ];

  // 使用 columns hook
  const { columns: tableColumns } = useColumns({
    columns: baseColumns,
    showIndex: true,
  });

  const generateQuestion = () => {
    const num1 = Math.floor(Math.random() * 50);
    const num2 = Math.floor(Math.random() * 50);
    setVerificationQuestion({ num1, num2 });
    setVerificationAnswer("");
  };

  const handleVerification = async () => {
    const correctAnswer = verificationQuestion.num1 + verificationQuestion.num2;
    if (Number(verificationAnswer) === correctAnswer) {
      try {
        await request.post("/products/delete", {
          id: verificationRecord?.id,
        });
        message.success("删除成功");
        actionRef.current?.reload();
        setVerificationModalVisible(false);
        setVerificationRecord(null);
      } catch (error) {
        message.error("删除失败");
      }
    } else {
      message.error("计算错误，请重试");
      generateQuestion();
    }
  };

  const handleDelete = (record: ProductItem) => {
    setVerificationRecord(record);
    setVerificationModalVisible(true);
    generateQuestion();
  };

  const handleSubmit = async (values: ProductItem) => {
    try {
      if (currentRecord) {
        // 更新
        await request.post("/products/update", {
          ...values,
          id: currentRecord.id,
        });
        message.success("更新成功");
      } else {
        // 创建
        await request.post("/products/create", values);
        message.success("创建成功");
      }
      setModalVisible(false);
      actionRef.current?.reload();
    } catch (error) {
      message.error(currentRecord ? "更新失败" : "创建失败");
    }
  };

  const handleCategoryChange = async (value: string) => {
    // setSelectedCategory(value);
    // setSelectedBrand(undefined);
    // if (value) {
    //   try {
    //     const response = await getBrandsByCategory(value);
    //     if (response.success) {
    //       setBrandOptions(
    //         response.data.list.map((brand: any) => ({
    //           label: brand.name,
    //           value: brand.id,
    //         }))
    //       );
    //     }
    //   } catch (error) {
    //     message.error("获取品牌列表失败");
    //   }
    // } else {
    //   setBrandOptions([]);
    // }
    // setQueryParams((prev) => ({
    //   ...prev,
    //   categoryId: value,
    //   brandId: undefined,
    //   current: 1,
    // }));
  };

  const getBrandsByCategory = async (categoryId: string) => {
    return await request.get("/brands/list", {
      params: { categoryId },
    });
  };

  useEffect(() => {
    // const fetchInitialData = async () => {
    //   try {
    //     const categoryRes = await getCategories();
    //     if (categoryRes.success) {
    //       setCategoryOptions(categoryRes.data.list.map((category: any) => ({
    //         label: category.name,
    //         value: category.id
    //       })));
    //     }
    //   } catch (error) {
    //     message.error(error);
    //   }
    // };
    // fetchInitialData();
  }, []);

  // 使用删除确认 hook
  const { confirmProps, showConfirm, currentId } = useDeleteConfirm({
    onDelete: async () => {
      if (!currentId) return;
      await handleRes({
        api: productApi.delete,
        data: currentId,
        success: {
          msg: "删除成功",
          callBack: () => {
            pageRef.current.onSearch({
              current: pageConfig.pagination.current,
              pageSize: pageConfig.pagination.pageSize,
            });
          },
        },
      });
    },
    onError: () => {
      message.error("删除失败");
    },
    title: "删除分类",
    content: "确定要删除这个分类吗？删除后不可恢复。",
  });

  // 使用 toolBar hook
  const { toolBarRender } = useToolBar({
    buttons: [
      {
        text: "新建",
        type: "primary",
        icon: <PlusOutlined />,
        onClick: () => {
          setCurrentRecord(undefined);
          setModalVisible(true);
        },
      },
    ],
  });

  const { optionColumn } = useColumnOptions<CategoryType>({
    actions: [
      {
        text: "编辑",
        onClick: (record) => {
          setCurrentRecord(record);
          setModalVisible(true);
        },
      },
      {
        text: "删除",
        type: "danger",
        onClick: (record) => showConfirm(record.id),
      },

      {
        text: "复制",
        type: "danger",
        onClick: (record) => handleCopy(record),
      },
    ],
    actionRef: pageConfig.actionRef,
  });

  const handleCopy = async (record: ProductItem) => {
    const res = await handleRes({
      api: productApi.copy,
      data: { id: record.id },
      success: {
        msg: true,
      },
    });
    pageRef.current.onSearch({
      current: pageConfig.pagination.current,
      pageSize: pageConfig.pagination.pageSize,
    });
  };

  return (
    <div>
      <PcPage
        pageRef={pageRef}
        columns={[...tableColumns, optionColumn]}
        toolBarRender={toolBarRender}
        {...pageConfig}
      />
      <DeleteConfirm {...confirmProps} />

      {modalVisible && (
        <Modal
          maskClosable={false}
          title={currentRecord ? "编辑商品" : "新建商品"}
          open={modalVisible}
          onCancel={() => {
            setModalVisible(false);
            setCurrentRecord(undefined);
          }}
          footer={null}
          width={800}
          destroyOnClose
        >
          <ProductForm initialValues={currentRecord} />
        </Modal>
      )}
    </div>
  );
};

export default ProductList;
